package com.seek.vod.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.seek.commonutils.ResponseResult;
import com.seek.eduservice.entity.EduVideo;
import com.seek.servicebase.exceptionhandler.SeekException;
import com.seek.vod.client.EduClient;
import com.seek.vod.service.VodService;
import com.seek.vod.utils.VodUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author: wml
 * @since: 2022/2/3 18:45
 */
@RestController
@RequestMapping("/eduvod/video")
public class VodController {

    @Autowired
    private VodService vodService;

    @Autowired
    private EduClient eduClient;

    // 上传视频到阿里云
    @PostMapping("uploadAlyVideo")
    public ResponseResult uploadAlyVideo(MultipartFile file) {
        // 返回上传视频之后的视频 id
        String videoId = vodService.uploadAlyVideo(file);
        return ResponseResult.ok().data("videoId", videoId);
    }

    // 根据视频 id 删除阿里云中的视频
    @DeleteMapping("removeAlyVideoByVideoSourceId/{videoSourceIds}")
    public ResponseResult removeAlyVideoByVideoSourceId(@PathVariable String videoSourceIds) {
        vodService.removeAlyVideoByVideoId(videoSourceIds);
        return ResponseResult.ok();
    }

    // 根据视频 id 删除阿里云中的视频，同时修改小节中的视频 id 和视频名称
    @DeleteMapping("removeAlyVideoByVideoSourceIdAndUpdateVideoByVideoId")
    public ResponseResult removeAlyVideoAndUpdateVideo(@RequestBody EduVideo eduVideo) {
        vodService.removeAlyVideoByVideoId(eduVideo.getVideoSourceId());
        eduVideo.setVideoSourceId("");
        eduVideo.setVideoOriginalName("");
        eduClient.updateById(eduVideo);
        return ResponseResult.ok();
    }

    // 删除多个阿里云视频的方法
    @DeleteMapping("deleteAlyVideoBatch")
    public ResponseResult deleteAlyVideoBatch() {
        return ResponseResult.ok();
    }

    // 根据视频 id 获取视频凭证
    @GetMapping("getVideoPlayAuthByVideoId/{alyVideoId}")
    public ResponseResult getVideoPlayAuthByVideoId(@PathVariable String alyVideoId) {
        DefaultAcsClient client = VodUtil.initVodClient();
        // 创建获取视频地址 request 和 response
        GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
        // 向 request 对象里面设置视频 id
        request.setVideoId(alyVideoId);
        // 调用初始化对象里面的方法，传递 request，获取数据
        GetVideoPlayAuthResponse response = null;
        try {
            response = client.getAcsResponse(request);
        } catch (ClientException e) {
            e.printStackTrace();
            throw new SeekException(20001, "获取视频播放凭证失败，请稍后重试。");
        }
        // 播放凭证
        String playAuth = response.getPlayAuth();
        return ResponseResult.ok().data("playAuth", playAuth);
    }

}
